package com.dg.river.core.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.dg.river.R;

/**
 * Created by hy on 2018/10/16
 * Description : Toast工具类
 */
public class ToastUtils {
    private static Handler handler = new Handler(Looper.getMainLooper());
    private static ToastUtils toastUtils;
    private static Toast toast1 = null;
    private static Object synObj = new Object();
    private Context context;
    private Toast toast;

    public static ToastUtils getInstance() {
        if (toastUtils == null) {
            synchronized (ToastUtils.class) {
                if (toastUtils == null) {
                    toastUtils = new ToastUtils();
                }
            }
        }
        return toastUtils;
    }

    public void init(Context context) {
        this.context = context;
    }

    public Toast toast(String str) {
        return displayToastShort(str);
    }

    /**
     * 显示Toast，duration为short
     *
     * @param str {@link String} 消息主体
     */
    public Toast displayToastShort(String str) {
        if (toast == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_toast, null);
            toast = new Toast(context);
            toast.setView(view);
            TextView tv_toast = view.findViewById(R.id.tv_toast);
            tv_toast.setText(str);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.setDuration(Toast.LENGTH_SHORT);
        } else {
            TextView tv_toast = toast.getView().findViewById(R.id.tv_toast);
            tv_toast.setText(str);
        }
        toast.show();
        return toast;
    }

    /**
     * 显示Toast，duration为long
     *
     * @param str {@link String} 消息主体
     */
    public void displayToastLong(String str) {
        Toast.makeText(context, str, Toast.LENGTH_LONG).show();
    }

    /**
     * 快速关闭toast
     * 不停的疯狂的点击某个按钮，触发了toast以后，toast内容会一直排着队的显示出来，不能很快的消失。这样可能会影响用户的使用。
     *
     * @param str {@link String} 消息主体
     */

    public void displayToastWithQuickClose(final String str) {
        new Thread(new Runnable() {

            public void run() {
                handler.post(new Runnable() {

                    public void run() {
                        synchronized (synObj) {
                            if (toast1 != null) {
                                toast1.setText(str);
                                toast1.setDuration(Toast.LENGTH_SHORT);
                            } else {
                                toast1 = Toast.makeText(context, str, Toast.LENGTH_SHORT);
                            }
                            toast1.show();
                        }
                    }
                });
            }
        }).start();
    }
}
